//
//  TruffleAppDelegate.m
//  Truffle
//
//  Created by Ismaila Kredity on 07/02/10.
//  Copyright kredity 2010. All rights reserved.
//

#import "TruffleAppDelegate.h"
#import "Accueil.h"
#import "Favoris.h"
#import "ServiceListViewController.h"
#import "Clients.h"
#import "CouponTableViewController.h"
#import "DAOTruffle.h"
#import "Coupon.h"
#import "Contact.h"
#import "Gateway.h"
#import "GatewayConnection.h"
#import "LoadAndSaveCoupons.h"
#import <CoreLocation/CoreLocation.h>

@implementation TruffleAppDelegate

@synthesize accueil;
@synthesize window;
@synthesize tabBarController;

#pragma mark -
#pragma mark Application lifecycle

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    
    // Override point for customization after app launch    
	
	//Copy database to the user's phone if needed.
	[self copyDatabaseIfNeeded];
	
	Clients * client = [[[Clients alloc] initWithNibName:@"Clients" bundle:nil] autorelease];
	UINavigationController * navClients = [[[UINavigationController alloc] initWithRootViewController:client] autorelease];
	
	ServiceListViewController * passerelles = [[[ServiceListViewController alloc] initWithNibName:@"Passerelles" bundle:nil] autorelease];
	UINavigationController * navPass = [[[UINavigationController alloc] initWithRootViewController:passerelles] autorelease];
	
	[self setAccueil:[[Accueil alloc] initWithNibName:@"Accueil" bundle:nil]];
	UINavigationController * navAccueil = [[[UINavigationController alloc] initWithRootViewController:accueil] autorelease];
	
	CouponTableViewController* couponViewController = 
	[[[CouponTableViewController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
	UINavigationController * navCoupns = [[[UINavigationController alloc] initWithRootViewController:couponViewController] autorelease];
	
	
	//Debut Push
	//NSLog(@"000000000000000000000000000000000000 je suis ici");
	//[self alertNotice:@"" withMSG:@"Initiating Remote Noticationss Are Active" cancleButtonTitle:@"Ok" otherButtonTitle:@""];
	[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)];
	
	//Fin push
	
	navClients.title = @"Contacts";
	navAccueil.title = @"Accueil";
	navPass.title = @"Services";
	navCoupns.title = @"Coupons";
	
	navClients.tabBarItem.image = [UIImage imageNamed:@"menu_contacts.png"];
	navAccueil.tabBarItem.image = [UIImage imageNamed:@"menu_accueil.png"];
	navPass.tabBarItem.image = [UIImage imageNamed:@"menu_services.png"];
	navCoupns.tabBarItem.image = [UIImage imageNamed:@"menu_coupons.png"];
	tabBarController.viewControllers = [NSArray arrayWithObjects: navAccueil, navPass, navClients, navCoupns, nil];	
	
	[window addSubview:[tabBarController view]];
	 
    [window makeKeyAndVisible];
}

/**
 applicationWillTerminate: saves changes in the application's managed object context before the application terminates.
 */
- (void)applicationWillTerminate:(UIApplication *)application {
	
    NSError *error;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
			// Handle error.
			NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
			exit(-1);  // Fail
        } 
    }
	
	// On récupère l'objet GatewayConnection.
	GatewayConnection *gatewayConnection = [[self accueil] gatewayConnection];
	
	// On se déconnecte de la passerelle
	if ([gatewayConnection disconnectWithAdd] < 0) {
		// FIXME : seulement un NSLog?
		NSLog(@"Impossible de se déconnecter de la passerelle.");
	}
	
	[accueil release];
}


#pragma mark -
#pragma mark Saving

/**
 Performs the save action for the application, which is to send the save:
 message to the application's managed object context.
 */
- (IBAction)saveAction:(id)sender {
	
    NSError *error;
    if (![[self managedObjectContext] save:&error]) {
		// Handle error
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		exit(-1);  // Fail
    }
}


#pragma mark -
#pragma mark Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *) managedObjectContext {
	
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }
	
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }
    return managedObjectContext;
}


/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
 */
- (NSManagedObjectModel *)managedObjectModel {
	
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    return managedObjectModel;
}


/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
	
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }
	
    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"Truffle.sqlite"]];
	
	NSError *error;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
        // Handle error
    }    
	
    return persistentStoreCoordinator;
}


#pragma mark -
#pragma mark Application's documents directory

/**
 Returns the path to the application's documents directory.
 */
- (NSString *)applicationDocumentsDirectory {
	
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}


- (void) copyDatabaseIfNeeded {
	
	//Using NSFileManager we can perform many file system operations.
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;
	
	NSString *dbPath = [self getDBPath];
	BOOL success = [fileManager fileExistsAtPath:dbPath];
	
	
	if(!success) {
		
		NSString * defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Database.sql"];
		
		success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
		
		if (!success){
			NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
			
		}
	}
}


- (NSString *) getDBPath {
	
	//Search for standard documents using NSSearchPathForDirectoriesInDomains
	//First Param = Searching the documents directory
	//Second Param = Searching the Users directory and not the System
	//Expand any tildes and identify home directories.
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
	NSString *documentsDir = [paths objectAtIndex:0];
	return [documentsDir stringByAppendingPathComponent:@"Database.sql"];
}



- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
	NSLog(@"devToken=%@",deviceToken);
	//Passer le Token à la connection
	[GatewayConnection setGlobalToken:deviceToken];
	
	//si l(utilisateur veut etre  viisible
	//[gatewayConnection initConnection];
	
	NSLog(@"Give the Token to teh connection");
	
	[self alertNotice:@"" withMSG:[NSString stringWithFormat:@"devToken=%@",deviceToken] cancleButtonTitle:@"Ok" otherButtonTitle:@""];
	
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { 
	NSLog(@"Error in registration. Error: %@", err);
	[self alertNotice:@"" withMSG:[NSString stringWithFormat:@"Error in registration. Error: %@", err] cancleButtonTitle:@"Ok" otherButtonTitle:@""];
}

-(void)alertNotice:(NSString *)title withMSG:(NSString *)msg cancleButtonTitle:(NSString *)cancleTitle otherButtonTitle:(NSString *)otherTitle{
	UIAlertView *alert;
	//LoadAndSaveCoupons * save = [[LoadAndSaveCoupons alloc] init];
	
	if([otherTitle isEqualToString:@""]){
		alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:cancleTitle otherButtonTitles:nil,nil];
		//afficher le message
		// sauvgaredr les coupons
		
		//[save saveCoupons];
		
	}else{ 
		alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:cancleTitle otherButtonTitles:otherTitle,nil];
	    // sauvgaredr les coupons
		//[save saveCoupons];
		[alert show]; 
		[alert release];
	}
	
}


#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	
    [managedObjectContext release];
    [managedObjectModel release];
    [persistentStoreCoordinator release];
    
	[window release];
	[super dealloc];
}


@end

